package com.decent.ejfadmin.utils;


import com.decent.ejfadmin.common.bean.MessageBean;
import com.decent.ejfadmin.common.bean.MultiResult;
import com.decent.ejfadmin.common.bean.SupUser;
import com.decent.ejfadmin.user.dao.UserDao;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;

/**
 * describe:财务用到的相关通用方法
 *
 * @author 陈豆豆
 * @date 2019/09/07
 */
@Component
public class FinanceUtils {
    @Autowired
    private UserDao userDao;

    /**
     * 会员批量添加加款申请数据校验
     *
     * @param data 源数据
     * @return
     */
    public MultiResult<MessageBean, StringBuffer> dataPreCheck(String data) {
        MultiResult<MessageBean, StringBuffer> returedResult = new MultiResult<>();
        //保存用户输入的会员信息
        HashSet<String> cachedUserSet = new HashSet<>();
        String[] split = StringUtils.split(data, "\r\n");
        if (split == null || split.length == 0) {
            return new MultiResult<>(MessageBean.fail("未获取到数据源!"));
        }
        StringBuffer dealData = new StringBuffer(split.length * 50);
        for (int i = 0; i < split.length; i++) {
            String perRecord = StringUtils.trim(split[i]);
            if (StringUtils.isBlank(perRecord)) {
                continue;
            }
            String[] perRecordItems = StringUtils.split(perRecord, "\t");
            if (perRecordItems == null || perRecordItems.length != 2) {
                return new MultiResult<>(MessageBean.fail("第" + (i + 1) + "条数据格式有误(会员编号    加款金额)"));
            }
            String userAccount = StringUtils.trim(perRecordItems[0]);
            if (StringUtils.isBlank(userAccount)) {
                return new MultiResult<>(MessageBean.fail("第" + (i + 1) + "条数据会员编号有误!"));
            }
            SupUser userFromDb = userDao.querySupUsersByAccount(userAccount);
            if (userFromDb == null) {
                return new MultiResult<>(MessageBean.fail("第" + (i + 1) + "条数据会员编号有误!未查询到该会员信息"));
            }
            if (!cachedUserSet.add(userAccount)) {
                return new MultiResult<>(MessageBean.fail("第" + (i + 1) + "条数据会员重复"));
            }
            double money = NumberUtils.toDouble(perRecordItems[1], 0D);
            if (money == 0) {
                return new MultiResult<>(MessageBean.fail("第" + (i + 1) + "条数据金额为0"));
            }
            dealData.append(userAccount).append(",").append(money).append(";");
        }
        returedResult.setRight(dealData);
        return returedResult;
    }


}
